package com.tabjin.rfidsocket.controller.v1.sys;

import com.tabjin.rfidsocket.authority.shiro.JwtUtil;
import com.tabjin.rfidsocket.authority.shiro.ThreadLocalToken;
import com.tabjin.rfidsocket.common.RequestHolder;
import com.tabjin.rfidsocket.common.utils.CookieUtils;
import com.tabjin.rfidsocket.common.utils.MD5Util;
import com.tabjin.rfidsocket.common.utils.TabJsonResult;
import com.tabjin.rfidsocket.exception.ParamException;
import com.tabjin.rfidsocket.pojo.ArchProjectBuildingUser;
import com.tabjin.rfidsocket.pojo.SysUser;
import com.tabjin.rfidsocket.pojo.bo.WxRegisterBO;
import com.tabjin.rfidsocket.pojo.vo.SysUserVO;
import com.tabjin.rfidsocket.service.access.ArchProjectService;
import com.tabjin.rfidsocket.service.sys.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tabjin
 * create at 2020/12/10 08:37
 * @program rfid_socket
 * @description
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ArchProjectService archProjectService;

    @Autowired
    private ThreadLocalToken threadLocalToken;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户登录
     *
     * @param request
     * @param response
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public TabJsonResult login(HttpServletRequest request,
                               HttpServletResponse response,
                               @RequestParam(value = "username") String username,
                               @RequestParam(value = "password") String password) throws IOException {

        Optional<SysUserVO> sysUserVOOptional = sysUserService.findByKeyword(username);
        SysUserVO sysUserVO = sysUserVOOptional.orElseThrow(() -> new ParamException("无用户"));

//        Optional<List<ArchProject>> projectByManagerIdOptional = archProjectService.getProjectByManagerId(sysUserVO.getId());
//        projectByManagerIdOptional.orElseThrow(() -> new ParamException(""));

        // TODO 根据用户id获取到项目项目
        Optional<List<ArchProjectBuildingUser>> projectIdByUserIdOptional = archProjectService.getProjectIdByUserId(sysUserVO.getId());
        List<ArchProjectBuildingUser> archProjectBuildingUserList = projectIdByUserIdOptional.orElseThrow(() -> new ParamException("该用户未绑定项目"));
        List<Integer> projectIdList = archProjectBuildingUserList.stream().map((archProjectBuildingUser -> {
            return archProjectBuildingUser.getProjectId();
        })).collect(Collectors.toList());


        String token = jwtUtil.createToken(sysUserVO.getId());

        RequestHolder.add(sysUserVO);
        String errorMsg = "";
        String ret = request.getParameter("ret");

        if (StringUtils.isBlank(username)) {
            return TabJsonResult.errorMessage("用户名不能为空");
        } else if (StringUtils.isBlank(password)) {
            return TabJsonResult.errorMessage("密码不能为空");
        } else if (sysUserVO == null) {
            return TabJsonResult.errorMessage("用户不存在");
        } else if (!sysUserVO.getPassword().equals(MD5Util.encrypt(password))) {
            return TabJsonResult.errorMessage("用户名或密码错误");
        } else if (sysUserVO.getStatus() != 1) {
            return TabJsonResult.errorMessage("用户状态为不可用，请联系管理员");
        } else {
            // 登录成功
//        CookieUtils.setCookie(request, response,
//                "user", JsonUtils.objectToJson(sysUserVO),
//                true);

            request.getSession().setAttribute("user", sysUserVO);
//            if (StringUtils.isNotBlank(ret)) {
//                response.sendRedirect(ret);
//            } else {
//                response.sendRedirect("/admin/index.page"); //TODO
//            }
        }
//            HttpSession session = request.getSession();
//            session.setAttribute("user", sysUserVO);
//
        request.setAttribute("error", errorMsg);
        request.setAttribute("username", username);

        Map<String, Object> map = new HashMap<>();
        map.put("res", sysUserVO);
        map.put("token", token);

        return TabJsonResult.ok(map);
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public TabJsonResult logout(HttpServletRequest request,
                                HttpServletResponse response,
                                @RequestParam String userId) {
        // 清除用户的相关信息的cookie
        CookieUtils.deleteCookie(request, response, "user");
        // 从session中移除已经登录的session
        request.getSession().invalidate();

        return TabJsonResult.ok();
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public TabJsonResult register(@RequestBody WxRegisterBO wxRegisterBO) {
        Optional<List<SysUser>> sysUserOptional = sysUserService.wxRegister(wxRegisterBO);
        List<SysUser> sysUserList = sysUserOptional.orElseThrow(() -> new ParamException("未获取到用户"));
        return TabJsonResult.ok(sysUserList);
    }
}
